Page({
    data: {
        question: '',
        answer: '',
        messages: []
    },
    bindQuestionInput: function(e) {
        this.setData({
            question: e.detail.value
        });
    },
    askQuestion: function() {
        const that = this;
        const questionContent = that.data.question.trim();

        if (!questionContent) {
            wx.showToast({
                title: '请输入问题',
                icon: 'none'
            });
            return;
        }

        const newMessage = {
            content: questionContent,
            type: 'self'
        };

        // 清空输入框并添加新消息
        this.setData({
            question: '',
            messages: [...this.data.messages, newMessage]
        });

        console.log('Sending request with data:', { question: questionContent }); // 调试信息

        wx.request({
            url: 'http://localhost:5002/api/ask', 
            method: 'POST',
            data: {
                question: questionContent // 使用保存的问题内容
            },
            header: {
                'content-type': 'application/json' // 默认值
            },
            success: function(res) {
                console.log('Request successful:', res); // 调试信息
                if (res.statusCode === 200) {
                    const timestamp = new Date().toLocaleString(); // 获取当前时间
                    const answerMessage = {
                        content: res.data.answer,
                        type: 'other'
                    };

                    that.setData({
                        messages: [...that.data.messages, answerMessage]
                    }, () => {
                        let allRecords = wx.getStorageSync('allQueryRecords') || [];
                        console.log("Before push:", allRecords); // 添加调试信息
                        allRecords.push({ question: questionContent, answer: res.data.answer, timestamp: timestamp }); // 添加时间戳
                        console.log("After push:", allRecords); // 添加调试信息
                        wx.setStorageSync('allQueryRecords', allRecords);
                        const checkData = wx.getStorageSync('allQueryRecords');
                        console.log("After save, data in storage:", checkData); 
                        console.log("Saved to storage:", wx.getStorageSync('allQueryRecords')); // 确认保存成功
                    });
                } else {
                    console.log('Failed to get answer:', res);
                    wx.showToast({
                        title: '获取答案失败，请稍后再试',
                        icon: 'none'
                    });
                }
            },
            fail: function(err) {
                console.log('Request failed:', err); // 调试信息
                wx.showToast({
                    title: '请求失败，请检查网络连接',
                    icon: 'none'
                });
            }
        });
    }
});